package MyTool

import (
	"WebSupervisor/MyTool/myjson"
	"WebSupervisor/message/cmd"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"strings"
)

type HttpHeader struct {
	Url        string
	Header     map[string]string
	response   *http.Response
	bodyString string
}

func NewHttpHeader(url string, header map[string]string) *HttpHeader {
	return &HttpHeader{Url: url, Header: header}
}
func (this *HttpHeader) Get(param string) *HttpHeader {
	client := &http.Client{}
	req, err := http.NewRequest("GET", this.Url+"?"+param, nil)
	if err != nil {
		// 处理错误
		cmd.Log("HttpClient Get req 失败", err)
	}
	for k, v := range this.Header {
		req.Header.Add(k, v)
	}
	resp, err := client.Do(req)
	if err != nil {
		// 处理错误
		cmd.Log("HttpClient Get resp 请求失败", err)
	}
	// 读取响应体
	this.response = resp
	return this
}
func (this *HttpHeader) Post(data map[string]string) *HttpHeader {
	client := &http.Client{}
	jsonBytsData, _ := json.Marshal(data)
	// 发送JSON数据
	jsonData := string(jsonBytsData)
	//jsonData := `{"name": "John Doe"}`
	req, err := http.NewRequest("POST", this.Url, strings.NewReader(jsonData))
	for k, v := range this.Header {
		req.Header.Add(k, v)
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		// 处理错误
		cmd.Log("HttpClient Post 请求失败", err)
	}

	this.response = resp

	return this
}
func (this *HttpHeader) Read() *HttpHeader {
	if this.response.StatusCode == http.StatusOK {
		bodyBytes, err := ioutil.ReadAll(this.response.Body)
		if err != nil {
			// 处理错误
			cmd.Log("HttpClient Read bodyBytes 读取失败", err)
		}
		this.bodyString = string(bodyBytes)
		// 使用响应内容
	} else {
		cmd.Log("HttpClient Read StatusCode 错误", this.response.StatusCode)
	}
	return this
}
func (this *HttpHeader) GetBodyString() string {
	//cmd.Log("HttpClient GetBodyString", this.bodyString)
	return this.bodyString
}
func (this *HttpHeader) Close() {
	err := this.response.Body.Close()
	if err != nil {
		return
	}
}
func (this *HttpHeader) JsonBodyOperate() myjson.MyJson {
	return myjson.MyJson{}
}
